﻿namespace WebServiceExtensions.Common
{
	#region Namespaces

    using System;
    using System.Reflection;
    using System.Security.Cryptography;
	using System.Text;
	using System.Web.Services.Configuration;

    #endregion

	/// <summary>
	///   Contains utility methods
	/// </summary>
	public static class Utils
	{
		#region Methods (2) 

		// Public Methods (2) 

        /// <summary>
        /// Registers the SOAP log extension.
        /// </summary>
        /// <param name="logExtensionType">
        /// The log Extension Type.
        /// </param>
        /// <param name="priority">
        /// The priority.
        /// </param>
        /// <param name="group">
        /// The group.
        /// </param>
        public static void RegisterSoapExtension(string logExtensionType, int priority, PriorityGroup group)
        {
            WebServicesSection wss = WebServicesSection.Current;

            FieldInfo readOnlyField = typeof(System.Configuration.ConfigurationElementCollection).GetField(
                "bReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
            if (readOnlyField != null)
            {
                readOnlyField.SetValue(wss.SoapExtensionTypes, false);
            }

            SoapExtensionTypeElement logExtension = new SoapExtensionTypeElement { Group = group, Type = Type.GetType(logExtensionType), Priority = priority };
            wss.SoapExtensionTypes.Add(logExtension);

            MethodInfo resetMethod = typeof(System.Configuration.ConfigurationElementCollection).GetMethod(
                "ResetModified", BindingFlags.NonPublic | BindingFlags.Instance);
            resetMethod.Invoke(wss.Protocols, null);
            MethodInfo setReadOnlyMethod = typeof(System.Configuration.ConfigurationElementCollection).GetMethod(
                "SetReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
            setReadOnlyMethod.Invoke(wss.SoapExtensionTypes, null);
        }

		/// <summary>
		///   Calculates the Md5 hash.
		/// </summary>
		/// <param name = "strInput">
		///   The STR input.
		/// </param>
		/// <returns>
		///   MD5 Hash
		/// </returns>
		public static string CalculateMd5Hash(string strInput)
		{
			MD5 md5 = MD5.Create();
			byte[] inputBytes = Encoding.ASCII.GetBytes(strInput);
			byte[] hash = md5.ComputeHash(inputBytes);

			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < hash.Length; i++)
			{
				sb.Append(hash[i].ToString("x2"));
			}

			return sb.ToString();
		}

		#endregion Methods 
	}
}